import { DirTreeNode as Node } from "../interface";

// 构建多叉树
export function buildTree(nodes: Node[]): Node[] {
  const nodeMap: { [key: number]: Node } = {};

  // 创建节点映射表
  for (const node of nodes) {
    node.children = [];
    nodeMap[node.id] = node;
  }

  const tree: Node[] = [];

  // 构建多叉树
  for (const node of nodes) {
    if (node.pid === 1) {
      tree.push(node);
    } else {
      const parentNode = nodeMap[node.pid];
      if (parentNode) {
        parentNode.children!.push(node);
      }
    }
  }

  return tree;
}
